<?php defined('BASEPATH') or exit('No direct script access allowed');

class Escort_user_m extends MY_Model {
	var $wtm_text = "HIGHESCOSTS.COM";
	
	function __construct(){
		parent::__construct();
		$this->load->library('image_lib');
		$this->load->helper('file');
		$this->wtm_text = read_file("./config/wtm_text.txt");
	}
	
	function submit_personal_info(){
		$personal_info_sex_id = $this->input->post('personal_info_sex_id', TRUE);
		$personal_info_public_sex = $this->input->post('personal_info_public_sex', TRUE);
		$personal_info_sexual_orientation_id = $this->input->post('personal_info_sexual_orientation_id', TRUE);
		$personal_info_public_sexual_orientation = $this->input->post('personal_info_public_sexual_orientation', TRUE);
		$personal_info_birthdate = $this->input->post('personal_info_birthdate', TRUE);
		$personal_info_public_birthdate = $this->input->post('personal_info_public_birthdate', TRUE);
		$personal_info_languages = isset($_POST['personal_info_languages']) ? implode(',', $_POST['personal_info_languages']):'';
		$personal_info_public_languages = $this->input->post('personal_info_public_languages', TRUE);
		//$personal_info_country_id = $this->input->post('country_id', TRUE);
		//$personal_info_state_id = $this->input->post('state_id', TRUE);
		//$personal_info_province_id = $this->input->post('province_id', TRUE);
		//$personal_info_city_id = $this->input->post('city_id', TRUE);
		//$personal_info_public_country = $this->input->post('personal_info_public_country', TRUE);
		$personal_info_breasts_size_id = $this->input->post('personal_info_breasts_size_id', TRUE);
		$personal_info_public_breasts_size = $this->input->post('personal_info_public_breasts_size', TRUE);
		$personal_info_penis_size_id = $this->input->post('personal_info_penis_size_id', TRUE);
		$personal_info_public_penis_size = $this->input->post('personal_info_public_penis_size', TRUE);
		$birthdateToTimeStamp = convertToTimeStampFromFormat($personal_info_birthdate,DATE_FORMAT);
		$personal_info_profession_id = $this->input->post('profession_id', TRUE);
		$personal_info_public_profession = $this->input->post('personal_info_public_profession', TRUE);
		$personal_info_borncountry_id = $this->input->post('borncountry_id', TRUE);
		$personal_info_public_borncountry = $this->input->post('personal_info_public_borncountry', TRUE);
		
		$USER = getAccountUserObject();
		$ESCORT = $this->escort_entity->init('user_id',$USER->getId());	
		$LOCKED = $this->locked_escort_entity->init('escort_id', $ESCORT->getId());
		
		$ESCORT->setSex($personal_info_sex_id);
		$ESCORT->setPublicSex($personal_info_public_sex);
		$ESCORT->setSexualOrientationId($personal_info_sexual_orientation_id);
		$ESCORT->setPublicSexualOrientation($personal_info_public_sexual_orientation);
		$ESCORT->setBirthDate($birthdateToTimeStamp);
		$ESCORT->setPublicBirthDate($personal_info_public_birthdate);
		$ESCORT->setLanguageIds($personal_info_languages);
		$ESCORT->setPublicLanguageIds($personal_info_public_languages);
		//$ESCORT->setCountryId($personal_info_country_id);
		//$ESCORT->setStateId($personal_info_state_id);
		//$ESCORT->setProvinceId($personal_info_province_id);
		//$ESCORT->setCityId($personal_info_city_id);
		//$ESCORT->setPublicCountry($personal_info_public_country);
		$ESCORT->setBreastsSizeId($personal_info_breasts_size_id);
		$ESCORT->setPublicBreastsSize($personal_info_public_breasts_size);
		$ESCORT->setPenisSizeId($personal_info_penis_size_id);
		$ESCORT->setPublicPenisSize($personal_info_public_penis_size);
		$ESCORT->setProfessionId($personal_info_profession_id);
		$ESCORT->setPublicProfession($personal_info_public_profession);
		$ESCORT->setBornCountryId($personal_info_borncountry_id);
		$ESCORT->setPublicBorncountry($personal_info_public_borncountry);
		$ESCORT->update();
		
		if( $this->input->post('isChangeDescFlag') != 0 ){	
			$language_array_code = array_filter(explode(',',getLanguagesSiteString_ioc()));
			$time = time();
			foreach($language_array_code as $code){
				$ESCORT->setTranslateMode( 
											intval($this->input->post("trans_mode_$code",TRUE)), 
											intval($this->input->post("lang_source_$code",TRUE)),
											$code, $ESCORT->getId() );
											
				$description = $this->input->post("personal_info_language_$code",TRUE);							
				$ESCORT->setDescription( trim($description), $code, $ESCORT->getId(), $time-- );
				/**							
				if(isset($_POST["personal_info_language_$code"])){
					$description = $this->input->post("personal_info_language_$code",TRUE);
					$old_desc = $ESCORT->getDescription($code, $ESCORT->getId());
					if( $old_desc ){
						if( strcmp( $description, $old_desc ) != 0){
							$ESCORT->setDescription( trim($description), $code, $ESCORT->getId(), $time-- );
						}
					}else{
						$ESCORT->setDescription( trim($description), $code, $ESCORT->getId(), $time-- );
					}
				}
				if(intval($this->input->post("trans_mode_$code",TRUE)) == 0){
					$ESCORT->setDescription(trim( $this->input->post("personal_info_language_$code",TRUE) ), $code, $ESCORT->getId(), $time--);
				}
				**/
			}
			$this->escort_description_entity->autoTranslate($ESCORT->getId());
		}
		
	//	
		$this->action_log->insertNewAction($USER->getId(),'log_action_edit_personal_info');
		echo "ok";
	}	
		
	function submit_appareance(){
		$appareance_hair_color_id = $this->input->post('appareance_hair_color_id', TRUE);
		$appareance_hair_long_id = $this->input->post('appareance_hair_long_id', TRUE);
		$appareance_hair_style_id = $this->input->post('appareance_hair_style_id', TRUE);
		$appareance_public_hair = $this->input->post('appareance_public_hair', TRUE);
		$appareance_eye_id = $this->input->post('appareance_eye_id', TRUE);
		$appareance_public_eye = $this->input->post('appareance_public_eye', TRUE);
		$appareance_height_id = $this->input->post('appareance_height_id', TRUE);
		$appareance_public_height = $this->input->post('appareance_public_height', TRUE);
		$appareance_weight_id = $this->input->post('appareance_weight_id', TRUE);
		$appareance_public_weight = $this->input->post('appareance_public_weight', TRUE);
		$appareance_measure1_id = $this->input->post('appareance_measure1_id', TRUE);
		$appareance_measure2_id = $this->input->post('appareance_measure2_id', TRUE);
		$appareance_measure3_id = $this->input->post('appareance_measure3_id', TRUE);
		$appareance_public_measures = $this->input->post('appareance_public_measures', TRUE);
		
		$USER = getAccountUserObject();
		$ESCORT = $this->escort_entity->init('user_id',$USER->getId());

		$ESCORT->setHairColorId($appareance_hair_color_id);
		$ESCORT->setHairSizeId($appareance_hair_long_id);
		$ESCORT->setHairStyleId($appareance_hair_style_id);
		$ESCORT->setPublicHair($appareance_public_hair);
		$ESCORT->setEyeId($appareance_eye_id);
		$ESCORT->setPublicEye($appareance_public_eye);
		$ESCORT->setHeight($appareance_height_id);
		$ESCORT->setPublicHeight($appareance_public_height);
		$ESCORT->setWeight($appareance_weight_id);
		$ESCORT->setPublicWeight($appareance_public_weight);
		$ESCORT->setMeasure1($appareance_measure1_id);
		$ESCORT->setMeasure2($appareance_measure2_id);
		$ESCORT->setMeasure3($appareance_measure3_id);
		$ESCORT->setPublicMeasures($appareance_public_measures);
		$ESCORT->update();
		
		$this->action_log->insertNewAction($USER->getId(),'log_action_edit_appareance');
		echo "ok";
	}	
		
	function submit_services(){
		$weekday_array = array_filter(explode(',', isset($_POST['services_weekdays']) ? implode(',', $_POST['services_weekdays']):'' ) );
		
		$USER = getAccountUserObject();
		$ESCORT = $this->escort_entity->init('user_id',$USER->getId());
		$LOCKED = $this->locked_escort_entity->init('escort_id', $ESCORT->getId());
		
		
		if($LOCKED->getLockedSchedule() != 1){
			$weekdaySelected = $ESCORT->getWeekdaysArray($ESCORT->getId());
			foreach($weekdaySelected as $id){
				if(! in_array($id,$weekday_array)){
					$this->db->where(array('escort_id'=>$ESCORT->getId(), 'week_day'=>$id))->delete(TBL_SCHEDULE);
				}
			}
			foreach($weekday_array as $id){
				$from = $this->input->post("services_time_from_$id",TRUE);
				$to = $this->input->post("services_time_to_$id",TRUE);
				$ESCORT->setSchedule($ESCORT->getId(), $id, $from, $to);
			}
		}
		
		$services_public_schedule = $this->input->post('services_public_schedule', TRUE);
		$services_public_calendar = $this->input->post('services_public_calendar', TRUE);
		$services_public_working_places = $this->input->post('services_public_working_places', TRUE);
		$services_public_travels = $this->input->post('services_public_travels',TRUE);
		$services_public_serves = $this->input->post('services_public_serves', TRUE);
		$services_public_services = $this->input->post('services_public_services', TRUE);
		
		$services_working_places_ids = isset($_POST['services_working_places']) ? implode(',', $_POST['services_working_places']):'';
		$services_travels_ids = isset($_POST['services_travels']) ? implode(',', $_POST['services_travels']):'';
		$services_serves_ids = isset($_POST['services_serves']) ? implode(',', $_POST['services_serves']):'';
		$services_services_ids = isset($_POST['services_services']) ? implode(',', $_POST['services_services']):'';
		
		$ESCORT->setPublicSchedule($services_public_schedule);
		$ESCORT->setPublicWorkingCalendar($services_public_calendar);
		$ESCORT->setPublicWorkingPlaces($services_public_working_places);
		$ESCORT->setPublicTravel($services_public_travels);
		$ESCORT->setPublicServesTo($services_public_serves);
		$ESCORT->setWorkingPlaceIds($services_working_places_ids);
		$ESCORT->setPublicServices($services_public_services);
		$ESCORT->setTravelIds($services_travels_ids);
		$ESCORT->setServesToIds($services_serves_ids);
		$ESCORT->setServiceIds($services_services_ids);
		$ESCORT->update();
		
		$this->action_log->insertNewAction($USER->getId(),'log_action_edit_services_info');
		echo "ok";
	}	
		
	function submit_rates(){
		$USER = getAccountUserObject();
		$ESCORT = $this->escort_entity->init('user_id',$USER->getId());
		
		$rates_payment_ids = isset($_POST['rates_payment']) ? implode(',', $_POST['rates_payment']) : '';
		$rates_public_payment = $this->input->post('rates_public_payment', TRUE);
		$rates_public_price = $this->input->post('rates_public_price', TRUE);
		$rates_transport_id = $this->input->post('rates_transport_id', TRUE);
		$rates_public_transport = $this->input->post('rates_public_transport', TRUE);
		$rates_extras_ids = isset($_POST['rates_extras']) ? implode(',', $_POST['rates_extras']) : '';
		$rates_public_extras = $this->input->post('rates_public_extras', TRUE);
		$rates_price_time_array = isset($_POST['rates_price_time']) ? ($_POST['rates_price_time']) : array();
		
		$ESCORT->setPaymentMethodIds($rates_payment_ids);
		$ESCORT->setPublicPaymentMethod($rates_public_payment);
		$ESCORT->setPublicPricingTime($rates_public_price);
		$ESCORT->setTransportIncludeId($rates_transport_id);
		$ESCORT->setPublicTransportInclude($rates_public_transport);
		$ESCORT->setExtrasIds($rates_extras_ids);
		$ESCORT->setPublicExtras($rates_public_extras);
		$ESCORT->update();
		
		$LOCKED = $this->locked_escort_entity->init('escort_id', $ESCORT->getId());
		
		if($LOCKED){
			if($LOCKED->getLockedPricingTime() != 1){
				$currentPricingTimeArray = $ESCORT->getPricingTimeIdArray($ESCORT->getId());
				foreach($currentPricingTimeArray as $id){
					if(! in_array($id, $rates_price_time_array)){
						$this->db->where(array('escort_id'=>$ESCORT->getId(), 'pricing_time_id'=>$id))->delete(TBL_PRICING_TIME);
					}
				}
				foreach($rates_price_time_array as $id){
					$price = $this->input->post("rates_price_value_$id", TRUE);
					$ESCORT->setPricingTime($ESCORT->getId(), $id, $price);
				}
			}
		}else{
			$currentPricingTimeArray = $ESCORT->getPricingTimeIdArray($ESCORT->getId());
			foreach($currentPricingTimeArray as $id){
				if(! in_array($id, $rates_price_time_array)){
					$this->db->where(array('escort_id'=>$ESCORT->getId(), 'pricing_time_id'=>$id))->delete(TBL_PRICING_TIME);
				}
			}
			foreach($rates_price_time_array as $id){
				$price = $this->input->post("rates_price_value_$id", TRUE);
				$ESCORT->setPricingTime($ESCORT->getId(), $id, $price);
			}
		}
		
		$this->action_log->insertNewAction($USER->getId(),'log_action_edit_rate_info');
		echo "ok";	
	}	
	
	function submit_contact_info(){
		$contact_lat = $this->input->post('contact_lat', TRUE);
		$contact_lng = $this->input->post('contact_lng', TRUE);
		$contact_info_phone = $this->input->post('contact_info_phone', TRUE);
		$contact_info_public_phone = $this->input->post('contact_info_public_phone', TRUE);
		$contact_info_email = $this->input->post('contact_info_email', TRUE);
		$contact_info_public_email = $this->input->post('contact_info_public_email', TRUE);
		$contact_info_address = $this->input->post('contact_info_address', TRUE);
		$contact_info_public_geolocalization = $this->input->post('contact_info_public_geolocalization', TRUE);
		$contact_info_show_address_on_map = $this->input->post('contact_info_show_address_on_map', TRUE);
		$contact_info_receive_message = $this->input->post('contact_info_receive_message', TRUE);
		$contact_info_public_address = $this->input->post('contact_info_public_address', TRUE);
		$contact_info_name =  $this->input->post('contact_info_name', TRUE);
		
		$USER = getAccountUserObject();
		$ESCORT = $this->escort_entity->init('user_id',$USER->getId());
		$LOCKED = $this->locked_escort_entity->init('escort_id', $ESCORT->getId());
		
		if(strlen($contact_info_name) == 0){
			echo "contact_info_name_err#".language_translate('contact_info_name_err');
			exit();
		}
		if(! $this->phpvalidator->is_email($contact_info_email)){
			echo "contact_info_email_err#".language_translate('contact_info_email_err');
			exit();
		}
	/*	$U = clone_($this->user_entity->init('email',$contact_info_email));
		if($U AND $U->getId() != $USER->getId()){
			echo "contact_info_email_err#".language_translate('contact_info_email_err2');
			exit();
		}
	*/	
		if($LOCKED){
			if($LOCKED->getLockedPhone() != 1){
				//$USER->setPhone($contact_info_phone);
				$ESCORT->setEscortPhone($contact_info_phone);
			}
			if($LOCKED->getLockedEmail() != 1){
				//$USER->setEmail($contact_info_email);
				$ESCORT->setEscortEmail($contact_info_email);
			}
			if($LOCKED->getLockedAddress() != 1){
				//$USER->setAddress($contact_info_address);
				$ESCORT->setEscortAddress($contact_info_address);
			}
			//$USER->update();
		}else{
			//$USER->setPhone($contact_info_phone);
			//$USER->setEmail($contact_info_email);
			//$USER->setAddress($contact_info_address);
			//$USER->update();
			$ESCORT->setEscortPhone($contact_info_phone);
			$ESCORT->setEscortEmail($contact_info_email);
			$ESCORT->setEscortAddress($contact_info_address);
		}
		$ESCORT->setEscortName($contact_info_name);
		$ESCORT->setGeolocation($contact_lat.'#'.$contact_lng);
		$ESCORT->setPublicGeolocation($contact_info_public_geolocalization);
		$ESCORT->setPublicPhone($contact_info_public_phone);
		$ESCORT->setPublicEmail($contact_info_public_email);
		$ESCORT->setPublicAddress($contact_info_public_address);
		$ESCORT->setShowAddressOnMap($contact_info_show_address_on_map);
		$ESCORT->setReceiveMessage($contact_info_receive_message);
		$ESCORT->update();
		
		$this->action_log->insertNewAction($USER->getId(),'log_action_edit_contact_info');
		echo "ok";
	}	
//////////////////////////////////////////////////////////////////////////////////////////////////	
// deprecated		
	function submit_new_image(){
		$USER = getAccountUserObject();
		$ESCORT = $this->escort_entity->init('user_id',$USER->getId());
		 
		if(($_FILES["upload_image"]['size']/1000000) > allowMaxFileSize() ){
			echo "File uploaded was greater than ".allowMaxFileSize()." Mb.";
			exit();
		}else{
			$upload_image = $this->module_helper->uploadFile( 
									$_FILES["upload_image"]['tmp_name'],
									$_FILES["upload_image"]['name'],
									$USER->getFolderFileStorage(),
									allowExtensionPictureUpload()
								);
			if(!$upload_image){
				echo "File uploaded error.";
				exit();
			}					
		}	
		$id = $this->media_entity->createNewMediaEntity();
		$MEDIA = $this->media_entity->init('id',$id);
		$MEDIA->setUserId($USER->getId());
		$MEDIA->setType('image');
		$MEDIA->setPermission('private');
		$MEDIA->setAltText('');
		$MEDIA->setDescText('');
		$MEDIA->setName($upload_image);
		$MEDIA->setOrdering($MEDIA->getCurrentOrdering($USER->getId())+1);
		$MEDIA->setClickedNo(0);
		$MEDIA->setAvatar('');
		$MEDIA->update();
		echo "ok";
	}	

// deprecated	
	function submit_new_video(){
		$USER = getAccountUserObject();
		$ESCORT = $this->escort_entity->init('user_id',$USER->getId());
	 	
		if(($_FILES["upload_video"]['size']/1000000) > allowMaxFileSize() ){
			echo "Video file uploaded was greater than ".allowMaxFileSize()." Mb.";
			exit();
		}else{
			$upload_video = $this->module_helper->uploadFile( 
									$_FILES["upload_video"]['tmp_name'],
									$_FILES["upload_video"]['name'],
									$USER->getFolderFileStorage(),
									allowExtensionVideoUpload()
								);
			if(!$upload_video){
				echo "Video file uploaded error.";
				exit();
			}					
		}	
		$upload_avatar = '';
		 
		if(($_FILES["upload_avatar"]['size']/1000000) > allowMaxFileSize() ){
			echo "Avatar file uploaded was greater than ".allowMaxFileSize()." Mb.";
			exit();
		}else{
			$upload_avatar = $this->module_helper->uploadFile( 
									$_FILES["upload_avatar"]['tmp_name'],
									$_FILES["upload_avatar"]['name'],
									$USER->getFolderFileStorage(),
									allowExtensionPictureUpload()
								);
			if(($_FILES["upload_avatar"]['size'] > 0)){
				if(!$upload_avatar){
					echo "Avatar file uploaded error.";
					exit();
				}
			}					
		}	
		
		$id = $this->media_entity->createNewMediaEntity();
		$MEDIA = $this->media_entity->init('id',$id);
		$MEDIA->setUserId($USER->getId());
		$MEDIA->setType('video');
		$MEDIA->setPermission('private');
		$MEDIA->setAltText('');
		$MEDIA->setDescText('');
		$MEDIA->setName($upload_video);
		$MEDIA->setOrdering($MEDIA->getCurrentOrdering($USER->getId())+1);
		$MEDIA->setClickedNo(0);
		$MEDIA->setAvatar($upload_avatar);
		$MEDIA->update();
		php2jsCallParentURL(site_url('escort_user/profile/pictures_videos')); 
		exit();
	}
////////////////////////////////////////////////////////////////////////////////////////////////////
	
	function submit_edit_media(){
		$USER = getAccountUserObject();
		
		$id = $this->input->post('id', TRUE);
		$alt_text = $this->input->post('alt_text', TRUE);
		$desc_text = $this->input->post('desc_text', TRUE);
		$MEDIA = $this->media_entity->init('id',$id);
		
		$upload_avatar = '';
		if(isset($_FILES["upload_avatar"])){
			if(($_FILES["upload_avatar"]['size']/1000000) > allowMaxFileSize() ){
				echo "Avatar file uploaded was greater than ".allowMaxFileSize()." Mb.";
				exit();
			}else{
				$upload_avatar = $this->module_helper->uploadFile( 
										$_FILES["upload_avatar"]['tmp_name'],
										$_FILES["upload_avatar"]['name'],
										$USER->getFolderFileStorage(),
										allowExtensionPictureUpload()
									);
				if(($_FILES["upload_avatar"]['size'] > 0)){
					if(!$upload_avatar){
						echo "Avatar file uploaded error.";
						exit();
					}
				}					
			}	
		}
		//if($MEDIA->getType() == 'image'){
			$MEDIA->setAltText($alt_text);
			$MEDIA->setDescText($desc_text);
			$MEDIA->setAvatar($upload_avatar);
		//}
		
		$MEDIA->update();
		
		$this->action_log->insertNewAction($USER->getId(),'log_action_update_media');
		echo 'ok';
	}
	
	function re_ordering(){
		$pos = array('public_top_media'=>'public_top', 'public_medias'=>'public', 'private_medias'=>'private');
		foreach($pos as $position =>$permission){
			$value = $this->input->post($position, TRUE);
			$id_array = array_filter( explode(',', $value ));
			$i =count($id_array) + 1;
			foreach($id_array as $id){
				$MEDIA = $this->media_entity->init('id',intval($id) );
				if($MEDIA){
					$MEDIA->setOrdering($i--);
					$MEDIA->setPermission($permission);
					$MEDIA->update();
				}
			}
		}
		$USER = getAccountUserObject();
		$this->action_log->insertNewAction($USER->getId(),'log_action_update_media');
		
		echo 'ok';
	}
	
	function image_face_censor(){
		$value = $this->input->post('value');
		$USER = getAccountUserObject();
		$ESCORT = $this->escort_entity->init('user_id',$USER->getId());
		$ESCORT->setImageFaceCensor($value);
		$ESCORT->update();
		exit();
	}
	
	function delete_media(){
		$id = $this->input->post('id', TRUE);
		$this->db->where('id',$id)->delete(TBL_MEDIA);
		
		$USER = getAccountUserObject();
		$this->action_log->insertNewAction($USER->getId(),'log_action_delete_media');
	}
	
	function loadAsyncDaysInMonth(){
		$year = $this->input->post('year',TRUE);
		$month = $this->input->post('month',TRUE);
		
		$USER = getAccountUserObject();
		$ESCORT = $this->escort_entity->init('user_id',$USER->getId());
		
		$WORKING_OBJ = $ESCORT->getWorkingCalendar($ESCORT->getId(), $year, $month);
		$dateArray = $WORKING_OBJ ? explode(',',$WORKING_OBJ->dates) : array() ;
		echo multi_checkbox($name_array = "days_in_month[]", $value_key_array= daysInMonthDataArray( $month, $year ), $value_checked=$dateArray, $divStyle='', $inputStyle ='', true);
	}

	function saveCalendarWorking_async(){
		$year = $this->input->post('year',TRUE);
		$month = $this->input->post('month',TRUE);
		$dateString = $this->input->post('date',TRUE);
		
		$USER = getAccountUserObject();
		$ESCORT = $this->escort_entity->init('user_id',$USER->getId());
		$LOCKED = $this->locked_escort_entity->init('escort_id', $ESCORT->getId());
		
		if($LOCKED){
			if($LOCKED->getLockedWorkingCalendar() != 1){
				$ESCORT->setWorkingCalendar($ESCORT->getId(),$year, $month, $dateString);
			}
		}else{
			$ESCORT->setWorkingCalendar($ESCORT->getId(),$year, $month, $dateString);
		}
		
		echo 'ok';
	}	
	
	function submit_image_file(){
		$USER = getAccountUserObject();
		$ESCORT = $this->escort_entity->init('user_id',$USER->getId());
		
		require_once('upload.php');
		// list of valid extensions, ex. array("jpeg", "xml", "bmp")
		$arr1 = allowExtensionPictureUpload();
		$arr2 = allowExtensionVideoUpload();
		$allowedExtensions = array_merge( $arr1 , $arr2 ); 
		// max file size in bytes
		$sizeLimit = allowMaxFileSize() * 1024*1024;

		$uploader = new qqFileUploader($allowedExtensions, $sizeLimit);
		$result = $uploader->handleUpload($USER->getFolderFileStorage());
		if(isset($result['success']) AND $result['success']){
			$sExtension = substr( $result['filename'], ( strrpos($result['filename'], '.') + 1 ) ) ;
			$sExtension = strtolower( $sExtension ) ;
			$type = in_array($sExtension,allowExtensionPictureUpload()) ? 'image':'video';
			$id = $this->media_entity->createNewMediaEntity();
			$MEDIA = $this->media_entity->init('id',$id);
			$MEDIA->setEscortId($ESCORT->getId());
			$MEDIA->setType($type);
			$MEDIA->setPermission('private');
			$MEDIA->setAltText('');
			$MEDIA->setDescText('');
			$originalFile = $this->renameMediaFileUpload($MEDIA, $result['filename']);
			$MEDIA->setName($originalFile);
			if($type == 'image'){
				$MEDIA->setPublicTopImageBig($this->processTopBigPicture($MEDIA, $originalFile));
				$MEDIA->setPublicTopImageThin($this->processTopThinPicture($MEDIA, $originalFile));
				$MEDIA->setPublicImage($this->processPublicPicture($MEDIA, $originalFile));
			}
			$MEDIA->setOrdering($MEDIA->getCurrentOrdering($ESCORT->getId())+1);
			$MEDIA->setClickedNo(0);
			$MEDIA->setAvatar('');
			$MEDIA->update();
			
			$this->action_log->insertNewAction($USER->getId(),'log_action_upload_media');
		}
		// to pass data through iframe you will need to encode all html tags
		echo htmlspecialchars(json_encode($result), ENT_NOQUOTES);
	}
	
	private function renameMediaFileUpload( $MEDIA, $oldFile){
		$ESCORT = $this->escort_entity->init('id',$MEDIA->getEscortId());
		
		$sExtension = strtolower ( substr( $oldFile, ( strrpos($oldFile, '.') + 1 ) ) );
		$newFile = "file_media_".$MEDIA->getId().".$sExtension";
		rename ( "./uploads/default/users/".$ESCORT->getUserId()."/".$oldFile, 
					"./uploads/default/users/".$ESCORT->getUserId()."/".$newFile	);
		return $newFile;			
	}
	
	private function processTopBigPicture($MEDIA, $originalFileName){
		$ESCORT = $this->escort_entity->init('id',$MEDIA->getEscortId());
		$sExtension = strtolower ( substr( $originalFileName, ( strrpos($originalFileName, '.') + 1 ) ) );
		$newFile = "file_media_top_big_".$this->digit->rand_digit(5)."_".$MEDIA->getId().".$sExtension";
		copy ( "./uploads/default/users/".$ESCORT->getUserId()."/".$originalFileName, 
					"./uploads/default/users/".$ESCORT->getUserId()."/".$newFile	);
	
		$config['source_image'] = "./uploads/default/users/".$ESCORT->getUserId()."/".$newFile;
		//$config['x_axis'] = '0';
		//$config['y_axis'] = '0';
		$config['create_thumb'] = TRUE;
		$config['maintain_ratio'] = TRUE;
		$config['thumb_marker'] = "";
		
		$size	 = getimagesize($config['source_image']);
		$config['width'] = (PUBLIC_TOP_W >= $size[0]) ? $size[0]:PUBLIC_TOP_W;
		$config['height'] = (PUBLIC_TOP_H >= $size[1]) ?$size[1]:PUBLIC_TOP_H;
		
		$this->image_lib->initialize($config);
		//$this->image_lib->crop();
		$this->image_lib->resize();
		$this->image_lib->clear();
		
		$config['source_image'] = "./uploads/default/users/".$ESCORT->getUserId()."/".$newFile;
		$size	 = getimagesize($config['source_image']);
		$config['width'] = (PUBLIC_TOP_W >= $size[0]) ? $size[0]:PUBLIC_TOP_W;
		$config['height'] = (PUBLIC_TOP_H >= $size[1]) ?$size[1]:PUBLIC_TOP_H;
		
		$this->wtm_center("./uploads/default/users/".$ESCORT->getUserId()."/".$newFile, $this->wtm_text,$margin_top= ($config['height'] - 76)/2 );
		$this->wtm_bottom_left("./uploads/default/users/".$ESCORT->getUserId()."/".$newFile, $this->wtm_text,$margin_top= ($config['height'] - 76) );
				
		return $newFile;				
	}
	
	private function processTopThinPicture($MEDIA, $originalFileName){
		$ESCORT = $this->escort_entity->init('id',$MEDIA->getEscortId());
		$sExtension = strtolower ( substr( $originalFileName, ( strrpos($originalFileName, '.') + 1 ) ) );
		$newFile = "file_media_top_thin_".$this->digit->rand_digit(5)."_".$MEDIA->getId().".$sExtension";
		copy ( "./uploads/default/users/".$ESCORT->getUserId()."/".$originalFileName, 
					"./uploads/default/users/".$ESCORT->getUserId()."/".$newFile	);
		
		$config['source_image'] = "./uploads/default/users/".$ESCORT->getUserId()."/".$newFile;
		$config['x_axis'] = '0';
		$config['y_axis'] = '0';
		//$config['create_thumb'] = TRUE;
		$config['maintain_ratio'] = FALSE;
		//$config['thumb_marker'] = "";
		
		$size	 = getimagesize($config['source_image']);
		$config['width'] = (TOP_THIN_W >= $size[0]) ? $size[0]:TOP_THIN_W;
		$config['height'] = (TOP_THIN_H >= $size[1]) ?$size[1]:TOP_THIN_H;
		 
		
		$this->image_lib->initialize($config);
		$this->image_lib->crop();
		//$this->image_lib->resize();
		$this->image_lib->clear();
		
		$config['source_image'] = "./uploads/default/users/".$ESCORT->getUserId()."/".$newFile;
		$size	 = getimagesize($config['source_image']);
		$config['width'] = (TOP_THIN_W >= $size[0]) ? $size[0]:TOP_THIN_W;
		$config['height'] = (TOP_THIN_H >= $size[1]) ?$size[1]:TOP_THIN_H;
			
		$this->wtm_center("./uploads/default/users/".$ESCORT->getUserId()."/".$newFile, $this->wtm_text,$margin_top= $config['height']-105);
		return $newFile;				
	}
	
	private function processPublicPicture($MEDIA, $originalFileName){
		$ESCORT = $this->escort_entity->init('id',$MEDIA->getEscortId());
		$sExtension = strtolower ( substr( $originalFileName, ( strrpos($originalFileName, '.') + 1 ) ) );
		$newFile = "file_media_public_".$this->digit->rand_digit(5)."_".$MEDIA->getId().".$sExtension";
		copy ( "./uploads/default/users/".$ESCORT->getUserId()."/".$originalFileName, 
					"./uploads/default/users/".$ESCORT->getUserId()."/".$newFile	);
		
		$config['source_image'] = "./uploads/default/users/".$ESCORT->getUserId()."/".$newFile;
		//$config['x_axis'] = '0';
		//$config['y_axis'] = '0';
		$config['create_thumb'] = TRUE;
		$config['maintain_ratio'] = TRUE;
		$config['thumb_marker'] = "";
		
		$size	 = getimagesize($config['source_image']);
		$config['width'] = (PUBLIC_W >= $size[0]) ? $size[0]:PUBLIC_W;
		$config['height'] = (PUBLIC_H >= $size[1]) ?$size[1]:PUBLIC_H;
		
		$this->image_lib->initialize($config);
		//$this->image_lib->crop();
		$this->image_lib->resize();
		$this->image_lib->clear();
		
		$config['source_image'] = "./uploads/default/users/".$ESCORT->getUserId()."/".$newFile;
		$size	 = getimagesize($config['source_image']);
		$config['width'] = (PUBLIC_W >= $size[0]) ? $size[0]:PUBLIC_W;
		$config['height'] = (PUBLIC_H >= $size[1]) ?$size[1]:PUBLIC_H;
		
		$this->wtm_center("./uploads/default/users/".$ESCORT->getUserId()."/".$newFile, $this->wtm_text,$margin_top= ($config['height']-84)/2);
		$this->wtm_bottom_left("./uploads/default/users/".$ESCORT->getUserId()."/".$newFile, $this->wtm_text,$margin_top= $config['height']-84);
				
		return $newFile;				
	}
	
	private function wtm_center($file, $text, $margin_top= 250){
		$config['source_image'] = $file;
		$config['wm_text'] = $text;
		$config['wm_type'] = 'text';
		$config['wm_font_path'] = './captcha/fonts/arial.ttf';
		$config['wm_font_size'] = '14';
		$config['wm_font_color'] = '#aaaaaa';
		$config['wm_vrt_alignment'] = 'center';
		$config['wm_hor_alignment'] = 'center';
		$config['wm_hor_offset'] = '0';
		$config['wm_vrt_offset'] = "$margin_top";
		$this->image_lib->initialize($config);
		$this->image_lib->watermark();	
		$this->image_lib->clear();
	}
	
	private function wtm_bottom_left($file, $text, $margin_top= 500){
		$config['source_image'] = $file;
		$config['wm_overlay_path'] = './config/wtm_image.png';
		$config['wm_type'] = 'overlay';
		$congif['wm_opacity'] = 80;
		//$config['wm_font_path'] = './captcha/fonts/arial.ttf';
		//$config['wm_font_size'] = '14';
		//$config['wm_font_color'] = '#aaaaaa';
		$config['wm_vrt_alignment'] = 'top';
		$config['wm_hor_alignment'] = 'left';
		$config['wm_hor_offset'] = '50';
		$config['wm_vrt_offset'] = "$margin_top";
		$this->image_lib->initialize($config);
		$this->image_lib->watermark();	
		$this->image_lib->clear();
	}
	
//end class	 
}